package com.sdkj.dspservice.modules.sys.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdkj.dspservice.common.base.entity.BaseResult;
import com.sdkj.dspservice.common.constant.HttpStatus;
import com.sdkj.dspservice.common.react.AntdProResult;
import com.sdkj.dspservice.common.utils.CollectionsUtils;
import com.sdkj.dspservice.common.utils.StringUtils;
import com.sdkj.dspservice.modules.sys.entity.Menu;
import com.sdkj.dspservice.modules.sys.entity.Role;
import com.sdkj.dspservice.modules.sys.entity.RoleMenu;
import com.sdkj.dspservice.modules.sys.service.MenuService;
import com.sdkj.dspservice.modules.sys.service.RoleMenuService;
import com.sdkj.dspservice.modules.sys.service.RoleService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色表Controller
 *
 * @author tm
 */
@RestController
@RequestMapping(value = "${project-config.apiUrl}/${project-config.version}/sys/role")
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private MenuService menuService;

    @RequiresPermissions("sys:role:view")
    @RequestMapping(value = "get")
    public AntdProResult get(String id) {
        AntdProResult result = new AntdProResult();
        if (StringUtils.isNotBlank(id)) {
            Role role = roleService.getById(id);
            result.setData(role);
        } else {
            result.error(HttpStatus.STATUS_400,
                    "id不能为空");
        }
        return result;
    }

    @RequiresPermissions("sys:role:view")
    @RequestMapping(value = "list")
    public AntdProResult list(Role role) {
        AntdProResult result = new AntdProResult();
        Page<Role> rolePage = roleService.page(new Page<>(role.current, role.pageSize), new QueryWrapper<>(role));
        result.success(rolePage);
        return result;
    }

    /**
     * 通过角色id，获取菜单id列表
     *
     * @param id
     * @return
     */
    @RequiresPermissions("sys:role:view")
    @RequestMapping(value = "menuIdListByRoleId")
    public AntdProResult menuIdListByRoleId(String id) {
        AntdProResult result = new AntdProResult();
        RoleMenu searchRoleMenu = new RoleMenu();
        searchRoleMenu.setRoleId(id);
        List<RoleMenu> roleMenuList = roleMenuService.list(searchRoleMenu);
        // map中存入所有结点id和所有叶子结点id
        Map<String, Object> map = new HashMap<>();
        List<String> allMenuIdList = new ArrayList<>();
        List<String> leafMenuIdList = new ArrayList<>();
        if (CollectionsUtils.isNotEmpty(roleMenuList)) {
            for (RoleMenu roleMenu : roleMenuList) {
                String menuId = roleMenu.getMenuId();
                if (StringUtils.isNotBlank(menuId)) {
                    // 插入全部结点
                    allMenuIdList.add(menuId);
                    // 判断是否为叶子结点
                    List<Menu> children = menuService.findByParentId(menuId);
                    if(CollectionsUtils.isEmpty(children)){
                        // children长度为0，说明是叶子结点
                        leafMenuIdList.add(menuId);
                    }
                }
            }
        }
        map.put("all", allMenuIdList);
        map.put("leaf", leafMenuIdList);
        result.success(map);
        return result;
    }

    @RequiresPermissions("sys:role:edit")
    @RequestMapping(value = "save", produces = MediaType.APPLICATION_JSON_VALUE)
    public BaseResult save(@Valid @RequestBody Role role) {
        BaseResult result = new BaseResult();
        roleService.saveOrUpdate(role);
        return result;
    }

    @RequiresPermissions("sys:role:edit")
    @RequestMapping(value = "remove")
    public BaseResult delete(String id, HttpServletResponse response) {
        BaseResult result = new BaseResult();
        if (StringUtils.isNotBlank(id)) {
            roleService.removeById(id);
        } else {
            response.setStatus(HttpStatus.STATUS_400);
            result.setErrorMessage("id不能为空");
        }
        return result;
    }

    /**
     * 获取数据源select列表
     *
     * @param role
     * @return
     */
    @ApiOperation(value = "获取select列表")
    @GetMapping(value = "listForSelect")
    public AntdProResult listForSelect(Role role) {
        AntdProResult result = new AntdProResult();
        List<Role> roleList = roleService.list(role);
        // 转换为{label:xxx,value:xxx}
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Role r : roleList) {
            Map<String, Object> map = new HashMap<>(2);
            map.put("label", r.getName());
            map.put("value", r.getId());
            mapList.add(map);
        }
        result.success(mapList);
        return result;
    }

}